package com.smart.manager.union.mall.repository;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.lang.Assert;
import cn.hutool.core.lang.Opt;
import com.smart.common.entities.constant.ArcoTips;
import com.smart.common.entities.core.Page;
import com.smart.manager.member.entities.models.MemberPigSale;
import com.smart.manager.union.mall.body.RUnionMallGoods;
import com.smart.manager.union.mall.models.UnionMallGoods;
import com.smart.manager.union.mall.models.query.QUnionMallGoods;
import com.smart.wap.bodys.UnionMallBody;
import io.ebean.DB;
import lombok.RequiredArgsConstructor;
import lombok.extern.log4j.Log4j2;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;

/**
 * 帮助中心
 * @author leo
 * @date 2023/07/26
 */
@Service
@Log4j2
@RequiredArgsConstructor
public class UnionMallGoodsRepository {

    /**
     * 查询搜索
     * @param search 搜索
     * @return {@link Page}<{@link UnionMallGoods}>
     */
    public Page<UnionMallGoods> pageList(RUnionMallGoods.SearchBody search) {
        QUnionMallGoods query = new QUnionMallGoods();
        Opt.ofBlankAble(search.getTitle()).ifPresent(x -> query.title.contains(x));
        Opt.ofBlankAble(search.getKindCode()).ifPresent(x -> query.kind.code.eq(x));
        query.setFirstRow(search.firstRow()).setMaxRows(search.maxRows());
        return new Page<UnionMallGoods>().load(query.findPagedList());
    }

    /**
     * 添加
     * @param body 身体
     */
    public void add(RUnionMallGoods.EditBody body) {
        BeanUtil.copyProperties(body, UnionMallGoods.class).setSaleCount(0).save();
    }

    /**
     * 更新
     * @param id   id
     * @param body 身体
     */
    public void update(Long id, RUnionMallGoods.EditBody body) {
        QUnionMallGoods query = new QUnionMallGoods();
        UnionMallGoods record = query.id.eq(id).setMaxRows(1).findOne();
        Assert.notNull(record, ArcoTips.UPDATE_NOT_FOUND);
        BeanUtil.copyProperties(body, record);
        Objects.requireNonNull(record).update();
    }

    /**
     * 删除ids
     * @param ids id
     * @return int
     */
    public int delByIds(List<Long> ids) {
        List<UnionMallGoods> list = new QUnionMallGoods().id.in(ids).findList();
        Assert.notEmpty(list, ArcoTips.DELETE_NOT_FOUND);
        for (UnionMallGoods module : list) {
            log.warn("检查数据是否允许被删除  {}", module);
        }
        return DB.deleteAll(list);
    }


    public Page<UnionMallGoods> getGoodsPageList(UnionMallBody.SearchBody search) {
        QUnionMallGoods query = new QUnionMallGoods();
        Opt.ofBlankAble(search.getIcon()).ifPresent(x -> query.kind.icon.eq(x));
        query.setFirstRow(search.firstRow()).setMaxRows(search.maxRows());
        return new Page<UnionMallGoods>().load(query.findPagedList());
    }
}
